import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import DeveloperInfo from '../views/DeveloperInfo.vue'
import ProjectList from '../views/ProjectList.vue'
import PublishInfo from '../views/PublishInfo.vue'
import XTSReports from '../views/XTSReports.vue'
import NotFound from '../views/NotFound.vue'

const routes = [
  {
    path: '/',
    name: 'ProjectList',
    component: ProjectList,
    meta: { requiresAuth: true }
  },
  {
    path: '/developer-info',
    name: 'DeveloperInfo',
    component: DeveloperInfo,
    meta: { requiresAuth: true }
  },
  {
    path: '/publish-info',
    name: 'PublishInfo',
    component: PublishInfo,
    meta: { requiresAuth: true }
  },
  {
    path: '/xts-reports',
    name: 'XTSReports',
    component: XTSReports,
    meta: { requiresAuth: true }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  // 删除重复的 DeveloperInfo 路由
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth !== false)
  
  // 检查登录状态
  const checkLoginStatus = async () => {
    try {
      const response = await fetch('/api/auth/check', {
        credentials: 'include'  // 添加这行，确保发送cookie
      })
      return response.ok
    } catch (error) {
      return false
    }
  }

  const isAuthenticated = await checkLoginStatus()

  if (requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router